package com.UKIT.airtickets.Activities

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.room.Room
import com.UKIT.airtickets.DB.AppDatabase
import com.UKIT.airtickets.Service.LanguageManager
import com.UKIT.airtickets.Service.Handlers.RegistrationHandler
import com.UKIT.airtickets.Service.ValidationUtils
import com.UKIT.airtickets.databinding.RegistrationBinding

class RegistrationActivity : AppCompatActivity() {

    private lateinit var db: AppDatabase
    private lateinit var binding: RegistrationBinding
    private lateinit var registrationHandler: RegistrationHandler

    override fun attachBaseContext(newBase: Context) {
        super.attachBaseContext(LanguageManager.attachBaseContext(newBase))
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = RegistrationBinding.inflate(layoutInflater)
        setContentView(binding.root)

        db = Room.databaseBuilder(applicationContext, AppDatabase::class.java, "airtickets.db")
            .fallbackToDestructiveMigration()
            .build()

        registrationHandler = RegistrationHandler(this)

        binding.apply {
            regBtn.setOnClickListener {
                val login = loginInput.text.toString()
                val email = emailInput.text.toString()
                val password = passwordInput.text.toString()

                if (validateFields(login, email, password)) {
                    registrationHandler.registerUser(login, email, password)
                    navigateToAuthorization()
                } else {
                    Toast.makeText(this@RegistrationActivity, "Поля пустые или заполнены неверно!", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    private fun validateFields(login: String, email: String, password: String): Boolean {
        return ValidationUtils.checkIsEmail(email) && ValidationUtils.checkPasswordTrue(password) && ValidationUtils.checkUserName(login)
    }

    fun navigateToAuthorization() {
        runOnUiThread {
            val intent = Intent(this, AuthorizationActivity::class.java)
            intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK
            startActivity(intent)
        }
    }
}
